package controller;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/XHRServlet")
public class XHRServlet extends HttpServlet {
	// 序列化版本号，作用是在反序列化时检查类的版本是否一致
    private static final long serialVersionUID1 = 1L;
    // 已有的用户名数组
    private String[] users = {"张三", "李四", "王五"};
	private static final long serialVersionUID = 1L;

    public XHRServlet() {
        
    }

	
	public void init(ServletConfig config) throws ServletException {
		
	}

	
	public void destroy() {
		
	}

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 response.setContentType("text/html;charset=utf-8");
         // 新闻标题数组对应颜色
         String[] news = {"习主席复信里的中外情谊", "张继科199元录播课3小时卖了25万", "哈尔滨一冰雕多处血印？媒体核查",
        		 ""};
         String[] colors = {"pink", "lightgreen", "orange"};
         // 随机生成一个新闻标题   
         int index = (int) (Math.random() * news.length);
         String title = news[index];
         String color = colors[index];
         // 返回新闻标题   
		
		//response.getWriter().append("Served at: ").append(request.getContextPath());
         response.getWriter().write("<h3 style=\"color=" + color + "\">" + title + "</h3>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 // 设置请求编码格式
        request.setCharacterEncoding("UTF-8");
        // 设置响应编码格式
        response.setContentType("text/html;charset=UTF-8");
        // 获取请求参数
        String todo = request.getParameter("todo");
        System.out.println("todo: " + todo);
		//doGet(request, response);
        if ("check".equals(todo)) {
            // 获取用户名
            String username = request.getParameter("username");
            System.out.println("用户填入的 username: " + username);
            // 判断用户名是否已存在
            boolean flag = false;
            for (String user : users) {
                if (user.equals(username)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                System.out.println(username + " 已存在");
                response.getWriter().write("用户名已存在");
            } else {
                System.out.println(username + " 可用");
                response.getWriter().write("用户名可用");
            }
        } else if ("register".equals(todo)) {
            // 如果 todo 为 register，进行注册
            response.getWriter().write("注册成功");
            System.out.println("用户注册新账号：" + request.getParameter("username"));
        }
        
	}
}   
	


